package com.jsoft.controller;

import com.alibaba.fastjson.JSON;
import com.jsoft.entity.Enterprise;
import com.jsoft.entity.MyVoucher;
import com.jsoft.service.EnterpriseService;
import com.jsoft.service.MyVoucherService;
import com.jsoft.service.impl.EnterpriseServiceImpl;
import com.jsoft.service.impl.MyVoucherServiceImpl;
import com.jsoft.util.IsNumeric;
import com.jsoft.util.Message;
import com.jsoft.util.PageHelper;
import com.jsoft.util.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangxuehan
 * @email 2302630156@qq.com
 * @date 2023/2/20
 */
@WebServlet("*.vou")
@MultipartConfig
public class VoucherController extends HttpServlet {
    private MyVoucherService myVoucherService = new MyVoucherServiceImpl();
    private EnterpriseService enterpriseService = new EnterpriseServiceImpl();

    /**
     * get请求方法
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        String servletPath = request.getServletPath();
        String methodName = servletPath.substring(servletPath.lastIndexOf("/") + 1, servletPath.length() - 4);

        try {
            Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 全部凭证分页查询
     */
    protected void listAll(HttpServletRequest request, HttpServletResponse response) {
        PageHelper<MyVoucher> pageHelper = new PageHelper<>();
        /**
         * 处理当前页
         */
        String currentPage = request.getParameter("currentPage");
        currentPage = currentPage == null || ("".equals(currentPage)) ? "1" : currentPage.trim();
        /**
         * 设置当前页
         */
        pageHelper.setCurrentPage(Integer.parseInt(currentPage));

        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String min = request.getParameter("min");


        /**
         * 处理条件
         */
        String sqlVoucher = "";
        String no = request.getParameter("no");
        if (no == null || no.equals("")) {
        } else {
            sqlVoucher += " and no like '%" + no + "%'";
        }
        String enterpriseName = request.getParameter("enterpriseName");
        if (enterpriseName == null || enterpriseName.equals("")) {
        } else {
            sqlVoucher += " and enterpriseName = '" + enterpriseName + "'";
        }
        String openTime = request.getParameter("openTime");
        if (openTime == null || openTime.equals("")) {
        } else {
            sqlVoucher += " and openTime between'" + openTime + " 00:00:00' and '" + openTime + " 23:59:59'";
        }

        if (min == null || min.equals("")) {
        } else {
            if(!IsNumeric.isNumeric(min)){
               out.write(JSON.toJSONString(new Message(1001, "输入金额不合法")));
                return;
            }
                sqlVoucher += " and amount >= " + min + "0000";
        }
        String max = request.getParameter("max");
        if (max == null || max.equals("")) {
        } else {
            if(!IsNumeric.isNumeric(max)){
                out.write(JSON.toJSONString(new Message(1002, "输入最大金额不合法")));
                return;
            }
            sqlVoucher += " and amount <= " + max + "0000";
        }
        String id = request.getParameter("enterpriseId");

        /**
         * 设置当前页
         */
        /**
         * 带有分页功能的数据返回给前台
         */
        try {
            pageHelper.setTotal(myVoucherService.countVoucher(id, sqlVoucher));
            List<MyVoucher> list = myVoucherService.listVoucher(id, pageHelper.getStart(), pageHelper.getPageSize(), sqlVoucher);
            for (MyVoucher myVoucher : list) {
                if ("A".equals(myVoucher.getSource())) {
                    myVoucher.setSource("开单签收");
                }
                if ("B".equals(myVoucher.getSource())) {
                    myVoucher.setSource("转让留存");
                }
                if ("A".equals(myVoucher.getStatus())) {
                    myVoucher.setStatus("未转让");
                }
                if ("B".equals(myVoucher.getStatus())) {
                    myVoucher.setStatus("已转让");
                }
            }
            pageHelper.setData(list);
            out.write(JSON.toJSONString(new ResultUtil("page", pageHelper)));
            out.flush();
        } catch (Exception e) {
//            out.write(JSON.toJSONString(new Message(1002, "输入金额不合法")));
        } finally {
            out.close();
        }
    }

    /**
     * 开单企业
     */
    protected void openEnterprise(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String enterpriseId = request.getParameter("enterpriseId");
        int id = Integer.parseInt(enterpriseId);
        try {
            List<Enterprise> list = enterpriseService.listOtherEnterpriseName(id);
            out.write(JSON.toJSONString(new ResultUtil("open", list)));
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            out.close();
        }

    }

    protected void getVoucherId(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String enterpriseIdStr = request.getParameter("enterpriseId");
        Integer enterpriseId = Integer.parseInt(enterpriseIdStr);
        try {
            List<MyVoucher> voucherId = myVoucherService.findVoucherId(enterpriseId);
            List arrVoucherIds = new ArrayList();
            for (MyVoucher myVoucher : voucherId) {
                Integer id = myVoucher.getId();
                arrVoucherIds.add(id);
            }
            ;
            out.write(JSON.toJSONString(new ResultUtil("arrVoucherIds", arrVoucherIds)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            out.close();
        }
    }

    protected void checkNumber(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String num = request.getParameter("num");
        if (!IsNumeric.isNumeric(num)) {
            out.write(JSON.toJSONString(new Message(1001, "输入金额不合法")));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
